import React, { useState, useEffect } from 'react';
import { Button, Spin, Tree, message } from 'antd';
import type { DataNode } from 'antd/es/tree';
import ScienceDataPanel from '@/components/DataManagement/ScienceDataPanel';
import OtherDataPanel from '@/components/DataManagement/OtherDataPanel';
import { useNavigate } from 'react-router-dom';
import request from '@/utils/request';
import './DataManagement.css';

// 自定义TreeNode类型，扩展DataNode
interface TreeNode extends DataNode {
  pid?: string;
}

const DataManagement: React.FC = () => {
  // tab切换
  const [activeTreeTab, setActiveTreeTab] = useState<'science' | 'other' | null>(null);
  // 树相关状态
  const [treeDataState, setTreeDataState] = useState<DataNode[]>([]);
  const [otherTreeDataState, setOtherTreeDataState] = useState<DataNode[]>([]);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [otherExpandedKeys, setOtherExpandedKeys] = useState<React.Key[]>([]);
  const [treeSelected, setTreeSelected] = useState<string[]>([]);
  const [otherTreeSelected, setOtherTreeSelected] = useState<string[]>([]);
  const [dataKey, setDataKey] = useState<string>('');
  const [otherDataKey, setOtherDataKey] = useState('');
  const [treeLoading, setTreeLoading] = useState(false);
  const navigate = useNavigate();

  // tab切换时拉取树数据
  useEffect(() => {
    if (activeTreeTab === 'science') {
      fetchTreeData(1);
    } else if (activeTreeTab === 'other') {
      fetchTreeData(2);
    }
  }, [activeTreeTab]);

  // 初始化默认tab
  useEffect(() => {
    setActiveTreeTab('science');
  }, []);

  // 拉取树数据
  const fetchTreeData = async (dataType: number) => {
    setTreeLoading(true);
    try {
      const response = await request.get(`/Management/DirectoryTree`, {
        params: { data_type: dataType }
      });
      if (response.status === 200) {
        const transformTreeData = (items: any[], level = 1): DataNode[] => {
          return items.map((item) => ({
            title: item.name,
            key: item.value,
            className: level === 1 ? 'level-1-node' : level === 2 ? 'level-2-node' : '',
            children: item.children ? transformTreeData(item.children, level + 1) : []
          }));
        };
        const newTreeData = transformTreeData(response.data.data);
        // 展开所有节点，唯独不展开第一层级的第一个节点以外的节点，但这些未展开的一级节点的子节点全部展开
        let expandedKeys = [];
        if (newTreeData.length > 0) {
          // 第一个一级节点key加入expandedKeys
          expandedKeys.push(newTreeData[0].key);
          // 递归收集所有子节点key（不包括一级节点本身，除了第一个）
          const collectAllDescendantKeys = (nodes) => {
            let keys = [];
            nodes.forEach((node) => {
              if (node.children && node.children.length > 0) {
                keys = keys.concat(node.children.map(child => child.key));
                keys = keys.concat(collectAllDescendantKeys(node.children));
              }
            });
            return keys;
          };
          // 第一个一级节点递归收集所有子孙节点key（包括多层）
          if (newTreeData[0].children && newTreeData[0].children.length > 0) {
            expandedKeys = expandedKeys.concat(collectAllDescendantKeys([newTreeData[0]]));
          }
          // 其他一级节点递归收集所有子孙节点key（不包括本身）
          for (let i = 1; i < newTreeData.length; i++) {
            if (newTreeData[i].children && newTreeData[i].children.length > 0) {
              expandedKeys = expandedKeys.concat(collectAllDescendantKeys([newTreeData[i]]));
            }
          }
        }
        if (dataType === 1) {
          setTreeDataState(newTreeData);
          setExpandedKeys(expandedKeys);
        } else {
          setOtherTreeDataState(newTreeData);
          setOtherExpandedKeys(expandedKeys);
        }
      }
    } catch (error) {
      message.error(error?.message || '加载树形数据失败');
    } finally {
      setTreeLoading(false);
    }
  };

  // 检查节点是否可勾选
  const isNodeSelectable = (node, treeData, isOtherTree = false) => {
    if (isOtherTree) {
      // 只判断是否为第一层级
      const isFirstLevel = treeData.some((firstLevelNode) => firstLevelNode.key === node.key);
      return !isFirstLevel;
    }
    // 科学探测数据原有逻辑
    const isFirstLevel = treeData.some((firstLevelNode) => firstLevelNode.key === node.key);
    if (isFirstLevel) return false;
    const isSecondLevel = treeData.some((firstLevelNode) =>
      firstLevelNode.children?.some((secondLevelNode) => secondLevelNode.key === node.key)
    );
    if (isSecondLevel) return false;
    return true;
  };

  // 获取第一个可勾选的节点
  const getFirstSelectableNode = (nodes: DataNode[], isOtherTree = false): string | null => {
    if (isOtherTree) {
      for (const firstLevelNode of nodes) {
        if (firstLevelNode.children && firstLevelNode.children.length > 0) {
          return firstLevelNode.children[0].key as string;
        }
      }
      return null;
    }
    for (const firstLevelNode of nodes) {
      if (firstLevelNode.children) {
        for (const secondLevelNode of firstLevelNode.children) {
          if (secondLevelNode.children && secondLevelNode.children.length > 0) {
            return secondLevelNode.children[0].key as string;
          }
        }
      }
    }
    return null;
  };

  // 判断key是否在树数据中
  const isKeyInTree = (key: string, nodes: DataNode[]): boolean => {
    for (const node of nodes) {
      if (node.key === key) {
        return true;
      }
      if (node.children && isKeyInTree(key, node.children)) {
        return true;
      }
    }
    return false;
  };

  // 树数据变化时自动选中第一个可选节点
  useEffect(() => {
    if (activeTreeTab === 'science' && treeDataState.length > 0) {
      if (treeSelected.length > 0 && isKeyInTree(treeSelected[0], treeDataState)) {
        setDataKey(treeSelected[0]);
        return;
      }
      const firstSelectableKey = getFirstSelectableNode(treeDataState);
      if (firstSelectableKey) {
        setTreeSelected([firstSelectableKey]);
        setDataKey(firstSelectableKey);
      }
    }
    if (activeTreeTab === 'other' && otherTreeDataState.length > 0) {
      if (otherTreeSelected.length > 0 && isKeyInTree(otherTreeSelected[0], otherTreeDataState)) {
        setOtherDataKey(otherTreeSelected[0]);
        return;
      }
      const firstSelectableKey = getFirstSelectableNode(otherTreeDataState, true);
      if (firstSelectableKey) {
        setOtherTreeSelected([firstSelectableKey]);
        setOtherDataKey(firstSelectableKey);
      }
    }
  }, [treeDataState, otherTreeDataState, activeTreeTab]);

  // tab切换
  const handleTreeTabChange = (tab: 'science' | 'other') => {
    setActiveTreeTab(tab);
  };

  return (
    <div className="data-management-container">
      <div className="data-management-header">
        <div className="data-management-header-left">
          <Button type="primary" size="middle" onClick={() => {
            window.location.hash = '#/pds-service';
          }}>
            PDS数据集服务
          </Button>
          <div className="button-divider"></div>
          <Button type="primary" size="middle" onClick={() => {
            window.location.hash = '#/anomaly-detection';
          }}>
            异常数据检测
          </Button>
          <div className="button-divider"></div>
          <Button type="primary" size="middle" onClick={() => {
            window.location.hash = '#/gis-management';
          }}>
            GIS管理
          </Button>
        </div>
        <div className="data-management-header-right"></div>
      </div>
      {/* 主内容区域 */}
      <div className="data-management-page" style={{ display: 'flex', width: '100%', minWidth: '1200px' }}>
        {/* 左侧任务树 */}
        <div className="data-management-left" style={{ width: '350px', flexShrink: 0, marginRight: '16px' }}>
          <div className="data-management-left-content">
            <div style={{ display: 'flex', gap: 16, marginBottom: 12, alignItems: 'center', justifyContent: 'center' }}>
              <span
                className={`tree-title${activeTreeTab === 'science' ? ' active' : ''}`}
                style={{ cursor: 'pointer', fontSize: 16, marginRight: 12 }}
                onClick={() => handleTreeTabChange('science')}>
                科学探测数据
              </span>
              <span
                className={`tree-title${activeTreeTab === 'other' ? ' active' : ''}`}
                style={{  fontSize: 16, cursor: 'pointer' }}
                onClick={() => handleTreeTabChange('other')}>
                其他数据
              </span>
            </div>
            <div className="data-management-tree-container">
              <Spin spinning={treeLoading}>
                {activeTreeTab === 'science' && (
                  <Tree
				  	blockNode
                    treeData={treeDataState}
                    expandedKeys={expandedKeys}
                    onExpand={(keys, { expanded, node }) => {
                      // 判断是否为一级节点
                      const isFirstLevel = treeDataState.some((firstLevelNode) => firstLevelNode.key === node.key);
                      if (isFirstLevel) {
                        // 只影响一级节点展开状态，子节点key保持不变
                        const firstLevelKeys = treeDataState.map((n) => n.key);
                        let newExpandedKeys;
                        if (expanded) {
                          // 展开当前一级节点，移除其它一级节点key，保留子节点key
                          newExpandedKeys = [node.key, ...expandedKeys.filter((k) => !firstLevelKeys.includes(k) && k !== node.key)];
                        } else {
                          // 收起当前一级节点，只移除该key，保留其它key
                          newExpandedKeys = expandedKeys.filter((k) => k !== node.key);
                        }
                        setExpandedKeys(newExpandedKeys);
                      } else {
                        // 下级节点展开/收起，正常处理
                        setExpandedKeys(keys);
                      }
                    }}
                    selectedKeys={treeSelected}
                    onSelect={(selectedKeys, info) => {
                      if (selectedKeys.length === 0) {
                        return;
                      }
                      const isSelectable = isNodeSelectable(info.node, treeDataState);
                      if (isSelectable) {
                        setTreeSelected(selectedKeys.map(String));
                        setDataKey(selectedKeys[0] as string);
                      } else {
                        // 不可选择的节点，用于展开/收起子节点
                        const nodeKey = info.node.key;
                        const isExpanded = expandedKeys.includes(nodeKey);
                        
                        if (isExpanded) {
                          // 如果节点已展开，则收起
                          setExpandedKeys(expandedKeys.filter(key => key !== nodeKey));
                        } else {
                          // 如果节点未展开，则展开
                          setExpandedKeys([...expandedKeys, nodeKey]);
                        }
                        
                        // 清空选择状态
                        setTreeSelected([]);
                      }
                    }}
                    style={{ minHeight: 100 }}
                  />
                )}
                {activeTreeTab === 'other' && (
                  <Tree
				  	blockNode
                    treeData={otherTreeDataState}
                    expandedKeys={otherExpandedKeys}
                    onExpand={(keys, { expanded, node }) => {
                      const isFirstLevel = otherTreeDataState.some((firstLevelNode) => firstLevelNode.key === node.key);
                      if (isFirstLevel) {
                        const firstLevelKeys = otherTreeDataState.map((n) => n.key);
                        let newExpandedKeys;
                        if (expanded) {
                          newExpandedKeys = [node.key, ...otherExpandedKeys.filter((k) => !firstLevelKeys.includes(k) && k !== node.key)];
                        } else {
                          newExpandedKeys = otherExpandedKeys.filter((k) => k !== node.key);
                        }
                        setOtherExpandedKeys(newExpandedKeys);
                      } else {
                        setOtherExpandedKeys(keys);
                      }
                    }}
                    selectedKeys={otherTreeSelected}
                    onSelect={(selectedKeys, info) => {
                      if (selectedKeys.length === 0) {
                        return;
                      }
                      const isSelectable = isNodeSelectable(info.node, otherTreeDataState, true);
                      if (isSelectable) {
                        setOtherTreeSelected(selectedKeys.map(String));
                        setOtherDataKey(selectedKeys[0] as string);
                      } else {
                        // 不可选择的节点，toggle展开/收起状态
                        const nodeKey = info.node.key as string;
                        let newExpandedKeys;
                        if (otherExpandedKeys.includes(nodeKey)) {
                          // 当前是展开状态，收起
                          newExpandedKeys = otherExpandedKeys.filter((k) => k !== nodeKey);
                        } else {
                          // 当前是收起状态，展开
                          newExpandedKeys = [...otherExpandedKeys, nodeKey];
                        }
                        setOtherExpandedKeys(newExpandedKeys);
                        // 清除选中状态
                        setOtherTreeSelected([]);
                      }
                    }}
                    style={{ minHeight: 100 }}
                  />
                )}
              </Spin>
            </div>
          </div>
        </div>
        {/* 右侧主内容区 */}
        <ScienceDataPanel dataKey={dataKey} visible={activeTreeTab === 'science'} />
        <OtherDataPanel otherDataKey={otherDataKey} visible={activeTreeTab === 'other'} />
      </div>
    </div>
  );
};

export default DataManagement;
